package nancal.mp.service

import nancal.mp.db.mongo.mor
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.redis.proxy.RedisListProxy
import org.springframework.stereotype.Service
import org.springframework.util.AntPathMatcher

@Service
class UserPermisitionService {
    private fun userDenyApi(key:String) = RedisListProxy("user-deny-api:${key}")

    //判断用户是否可以访问Api

    fun allowAdminUserApi(token: String, roles: List<String>, requestURI: String): Boolean {
        var denyApis = userDenyApi(token).getListString()

        if (denyApis == null) {
            var urls = mutableSetOf<String>();


            mor.admin.adminRole.query().where { it.id  mongoIn roles }
                .select { it.permissionApis }
                .toList()
                .forEach {
                    urls.addAll(it.permissionApis.map { it.path })
                }


            var all = mor.admin.adminPermissionApi.query()
                .select { it.url }
                .toList()
                .map { it.url }

            denyApis = all.minus(urls);

            userDenyApi(token).push(*denyApis.toTypedArray())
        }

        var ant = AntPathMatcher();
        if (denyApis.any { ant.match(it, requestURI) }) {
            return false;
        }

        return true;
    }

}